<template>
  <div class="createPost-container">
    <el-form
      ref="postForm"
      :model="postForm"
      :rules="rules"
      class="form-container"
      :disabled="isView"
    >
      <div class="createPost-main-container">
        <el-row gutter="80">
          <div class="postInfo-container">
            <el-col :span="12">
              <el-row>
                <el-form-item label-width="180px" label="专家：" prop="id">
                  <el-input
                    v-model="postForm.specialistName"
                    :maxlength="100"
                    name="name"
                    required
                    placeholder="请选择专家"
                    @focus="focusUser"
                  >
                  </el-input>
                </el-form-item>
              </el-row>
              <el-row>
                <el-form-item
                  style="margin-bottom: 40px"
                  prop="employeeId"
                  label-width="180px"
                  label="员工编号："
                  :disabled="true"
                >
                  <el-input
                    v-model="postForm.employeeId"
                    :maxlength="100"
                    name="name"
                    required
                    placeholder="员工编号"
                  >
                  </el-input>
                </el-form-item>
              </el-row>
              <el-row>
                <el-form-item
                  style="margin-bottom: 40px"
                  prop="specialistSource"
                  label-width="180px"
                  label="专家来源："
                >
                  <template>
                    <el-radio v-model="postForm.specialistSource" label="校内"
                      >校内</el-radio
                    >
                    <el-radio v-model="postForm.specialistSource" label="校外"
                      >校外</el-radio
                    >
                  </template>
                </el-form-item>
              </el-row>
              <el-row>
                <el-form-item
                  style="margin-bottom: 40px"
                  prop="specialistEduBackground"
                  label-width="180px"
                  label="学历："
                >
                  <el-select
                    v-model="postForm.specialistEduBackground"
                    :remote-method="getBackgroundList"
                    filterable
                    remote
                    placeholder="请选择学历"
                    :loading="loading"
                    required
                  >
                    <el-option
                      v-for="item in backgroundListOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.label"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-row>
              <el-row>
                <el-form-item
                  style="margin-bottom: 40px"
                  prop="specialistEduDegree"
                  label-width="180px"
                  label="学位："
                >
                  <el-select
                    v-model="postForm.specialistEduDegree"
                    :remote-method="getDegreeList"
                    filterable
                    remote
                    placeholder="请选择学位"
                    :loading="loading"
                    required
                  >
                    <el-option
                      v-for="item in degreeListOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.label"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-row>
              <el-row>
                <el-form-item
                  style="margin-bottom: 40px"
                  prop="specialistCategory"
                  label-width="180px"
                  label="统计归属："
                >
                  <template>
                    <el-radio
                      v-model="postForm.specialistCategory"
                      label="科技类"
                      >科技类</el-radio
                    >
                    <el-radio
                      v-model="postForm.specialistCategory"
                      label="社科类"
                      >社科类</el-radio
                    >
                  </template>
                </el-form-item>
              </el-row>
            </el-col>

            <el-col :span="12">
              <el-row>
                <el-form-item
                  label-width="180px"
                  prop="specialistSubject"
                  label="一级学科："
                >
                  <el-select
                    v-model="postForm.specialistSubject"
                    :remote-method="getSubjectList"
                    filterable
                    remote
                    placeholder="请选择一级学科"
                    :loading="loading"
                    required
                  >
                    <el-option
                      v-for="item in subjectListOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.label"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-row>
              <el-row>
                <el-form-item
                  style="margin-bottom: 40px"
                  prop="specialistHonor"
                  label-width="180px"
                  label="荣誉称号："
                >
                  <template>
                    <el-radio v-model="postForm.specialistHonor" label="院士"
                      >院士</el-radio
                    >
                    <el-radio
                      v-model="postForm.specialistHonor"
                      label="杰出青年"
                      >杰出青年</el-radio
                    >
                    <el-radio v-model="postForm.specialistHonor" label="其他"
                      >其他</el-radio
                    >
                  </template>
                </el-form-item>
              </el-row>
              <el-row>
                <el-form-item
                  style="margin-bottom: 40px"
                  prop="specialistOrganization"
                  label-width="180px"
                  label="所属单位："
                >
                  <el-input
                    v-model="postForm.specialistOrganization"
                    :maxlength="100"
                    name="name"
                    required
                    placeholder="请输入所属单位"
                  >
                  </el-input>
                </el-form-item>
              </el-row>
              <el-row>
                <el-form-item
                  style="margin-bottom: 40px"
                  label-width="180px"
                  label="研究方向："
                >
                  <el-input
                    v-model="postForm.specialistDirection"
                    type="textarea"
                    class=""
                    :autosize="{ minRows: 4, maxRows: 8 }"
                    placeholder="请输入研究方向"
                  />
                </el-form-item>
              </el-row>
            </el-col>
          </div>
        </el-row>
      </div>
      <el-dialog title="人员信息" class="user-dialog-container" :visible.sync="dialogTableVisible">
        <div class="filter-container">
          <el-input
            v-model="listQuery.searchKey1"
            placeholder="员工号"
            style="width: 200px"
            class="filter-item"
          />
          <el-input
            v-model="listQuery.searchKey2"
            placeholder="姓名"
            style="width: 200px"
            class="filter-item"
          />
          <el-button
            class="filter-item"
            type="primary"
            icon="el-icon-search"
            @click="searchAndSort"
          >
            检索
          </el-button>
        </div>
        <el-table
          :key="tableKey"
          v-loading="listLoading"
          :data="list"
          border
          fit
          highlight-current-row
          style="width: 100%"
        >
          <el-table-column label="" min-width="20px" align="center">
            <template slot-scope="{ row }">
              <el-radio :label="row.id" 
                v-model="radio"
                @change.native="singleSelection(row)">&nbsp;</el-radio>
            </template>
          </el-table-column>
          <el-table-column label="员工号" min-width="50px" align="center">
            <template slot-scope="{ row }">
              <span class="link-type">{{ row.employeeId }}</span>
            </template>
          </el-table-column>
          <el-table-column label="名字" min-width="50px" align="center">
            <template slot-scope="{ row }">
              <span class="link-type">{{ row.userName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="性别" min-width="20px" align="center">
            <template slot-scope="{ row }">
              <span class="link-type">{{ row.userGender }}</span>
            </template>
          </el-table-column>
          <el-table-column label="电话号码" min-width="50px" align="center">
            <template slot-scope="{ row }">
              <span class="link-type">{{ row.userCellphone }}</span>
            </template>
          </el-table-column>
          <el-table-column label="身份证号码" min-width="50px" align="center">
            <template slot-scope="{ row }">
              <span class="link-type">{{ row.userId }}</span>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="listQuery.pageIndex"
          :limit.sync="listQuery.limit"
          @pagination="getList"
        />
      </el-dialog>
      <el-button
        v-loading="loading"
        style="margin-left: 230px; width: 100px"
        type="success"
        @click="submitForm"
      >
        保存
      </el-button>
    </el-form>
  </div>
</template>

<script>
import backgroundList from "@/data/educationBackgrounds";
import degreeList from "@/data/educationDegrees";
import subjectList from "@/data/subjects";
import { fetchUserList } from "@/api/user";
import {
  fetchSpecialistById,
  createSpecialist,
  updateSpecialist,
} from "@/api/specialist";
import Pagination from "@/components/Pagination";
import { searchTwo } from "@/utils";

const defaultForm = {
  id: undefined,
  specialistName: "", // 专家姓名
  employeeId: "", // 员工编号
  specialistSource: "", // 专家来源
  specialistEduBackground: "", // 专家学历
  specialistEduDegree: "", // 专家学位
  specialistCategory: "", // 专家统计归属
  specialistSubject: "", // 专家的一级学科
  specialistHonor: "", // 专家荣誉称号
  specialistOrganization: "", // 专家所属单位
  specialistDirection: "", // 专家研究方向
};

export default {
  name: "SpecialistDetail",
  components: { Pagination },
  props: {
    isEdit: {
      type: Boolean,
      default: false,
    },
    isView: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    const validateRequire = (rule, value, callback) => {
      if (!value || value === "") {
        callback(new Error("此为必填项"));
      } else {
        callback();
      }
    };

    return {
      postForm: Object.assign({}, defaultForm),
      loading: false,
      dialogTableVisible: false,
      userList: [],
      backgroundListOptions: backgroundList,
      degreeListOptions: degreeList,
      subjectListOptions: subjectList,
      tableKey: 0,
      totalList: null,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        pageIndex: 1,
        limit: 10,
        searchField1: "employeeId",
        searchField2: "userName",
        searchKey1: "",
        searchKey2: "",
        sortField: "id",
        sortKey: "asce",
      },
      radio: "",
      rules: {
        id: [{ required: true, validator: validateRequire }],
        specialistSource: [{ required: true, validator: validateRequire }],
        specialistEduBackground: [
          { required: true, validator: validateRequire },
        ],
        specialistEduDegree: [{ required: true, validator: validateRequire }],
        specialistCategory: [{ required: true, validator: validateRequire }],
        specialistSubject: [{ required: true, validator: validateRequire }],
        specialistHonor: [{ required: true, validator: validateRequire }],
      },
    };
  },
  created() {
    if (this.isEdit || this.isView) {
      const id = this.$route.params && this.$route.params.id;
      this.fetchData(id);
    }
  },
  methods: {
    getBackgroundList(query) {
      if (query !== "") {
        this.loading = true;
        this.backgroundListOptions = backgroundList.filter((item) => {
          return item.label.toLowerCase().indexOf(query.toLowerCase()) > -1;
        });
        this.loading = false;
      } else {
        this.backgroundListOptions = backgroundList;
      }
    },
    getDegreeList(query) {
      if (query !== "") {
        this.loading = true;
        this.degreeListOptions = degreeList.filter((item) => {
          return item.label.toLowerCase().indexOf(query.toLowerCase()) > -1;
        });
        this.loading = false;
      } else {
        this.degreeListOptions = degreeList;
      }
    },
    getSubjectList(query) {
      if (query !== "") {
        this.loading = true;
        this.subjectListOptions = subjectList.filter((item) => {
          return item.label.toLowerCase().indexOf(query.toLowerCase()) > -1;
        });
        this.loading = false;
      } else {
        this.subjectListOptions = subjectList;
      }
    },
    fetchData(id) {
      fetchSpecialistById(id)
        .then((res) => {
          this.postForm = res.data[0];
        })
        .catch((err) => {
          console.log(err);
        });
    },
    focusUser() {
      this.dialogTableVisible = true;
      this.getList();
    },
    getList() {
      this.listLoading = true;
      fetchUserList().then((res) => {
        this.totalList = res.data;
        this.handleFilter();

        this.listLoading = false;
      });
    },
    handleFilter() {
      const result = searchTwo(this.totalList, this.listQuery);
      this.list = result.data;
      this.total = result.total;
    },
    searchAndSort() {
      this.listQuery.pageIndex = 1;
      this.handleFilter();
    },
    singleSelection(row) {
      this.postForm.id = row.id;
      this.postForm.specialistName = row.userName;
      this.postForm.employeeId = row.employeeId;
      this.dialogTableVisible = false;
    },
    submitForm() {
      console.log(this.postForm);
      this.$refs.postForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          if (this.$route.path.includes("create")) {
            createSpecialist(this.postForm)
              .then((res) => {
                if (res.data) {
                  this.$router.push("/specialist/list");

                  this.$message({
                    title: "成功",
                    message: "专家创建成功",
                    type: "success",
                    duration: 2000,
                  });
                } else {
                  this.$message({
                    message: "专家创建失败",
                    type: "error",
                  });
                }
                this.loading = false;
              })
              .catch((err) => {
                this.loading = false;
              });
          } else {
            updateSpecialist(this.postForm.id, this.postForm)
              .then((res) => {
                if (res.data) {
                  this.$router.push("/specialist/list");
                  this.$message({
                    title: "成功",
                    message: "专家信息更新成功",
                    type: "success",
                    duration: 2000,
                  });
                } else {
                  this.$message({
                    message: "专家信息更新失败",
                    type: "error",
                  });
                }
                this.loading = false;
              })
              .catch((err) => {
                this.loading = false;
              });
          }
        } else {
          console.log("专家信息保存失败");
          return false;
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
@import "~@/styles/mixin.scss";

.createPost-container {
  position: relative;

  .createPost-main-container {
    padding: 40px 45px 20px 50px;

    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;

      .postInfo-container-item {
        float: left;
      }
    }
  }
}

.identity-container {
  margin-top: 50px;
}
</style>
